package cn.gx.kevin.common.tree;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gx.kevin.common.ui.ClientButton;

/**
 * @ClassName: TreeNode
 * @Description: 树形节点类
 * @author kevin.huang
 * @date 2014-9-26 上午9:44:18
 * @param <T>
 */
public class TreeNode<T> {

	public String id;
	public String pid;
	public String text;
	public T data;
	public int deep;
	public List<TreeNode<T>> children;
	public IListToTree<T> toTree = null;

	/**
	 * 不带按钮的tojson
	 ***/
	public JSONObject toJSON(Object extParams) throws Throwable {
		JSONObject obj = new JSONObject();
		obj.put("id", id);
		obj.put("pid", pid);
		obj.put("deep", deep);
		obj.put("text", text);
		obj.put("data", this.data);
		if (children != null) {
			JSONArray jarray = new JSONArray();
			for (TreeNode<T> n : children) {
				jarray.add(n.toJSON(extParams));
			}
			obj.put("children", jarray);
		}
		toTree.createNode(data, obj, extParams);
		return obj;
	}

	/***
	 * 带按钮的tojson
	 ***/
	public JSONObject toJSON(List<ClientButton> btnList, Object extParams) throws Throwable {
		JSONObject obj = new JSONObject();
		obj.put("id", id);
		obj.put("pid", pid);
		obj.put("deep", deep);
		obj.put("text", text);
		obj.put("data", this.data);
		JSONArray btnJsonList = new JSONArray();
		for (ClientButton btn : btnList) {
			ClientButton b = btn.copy();
			ClientButton tmp = toTree.createTreeButton(b, data, extParams);
			if (tmp != null && tmp.isVisualable()) {
				btnJsonList.add(tmp.toJSONObject());
			}
		}
		obj.put("toolbar", btnJsonList);
		if (children != null) {
			JSONArray jarray = new JSONArray();
			for (TreeNode<T> n : children) {
				jarray.add(n.toJSON(btnList, extParams));
			}
			obj.put("children", jarray);
		}
		toTree.createNode(data, obj, extParams);
		return obj;
	}
}
